package com.srwl.mytx.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.RecyclerView;

import com.srwl.mytx.Constant;
import com.srwl.mytx.EaseConstant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.activity.BaseActivity;
import com.srwl.mytx.activity.UserProfileActivity;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.UserService;
import com.srwl.mytx.utils.ClickUtil;
import com.srwl.mytx.utils.GlideLoadUtils;
import com.srwl.mytx.widget.ConfirmDialog;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class FollowFansRecordAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private final List<User> fansList;
    private final Context context;
    private boolean bol_noData;//标记是否有数据
    private boolean bol_requestError;//标记是否有数据
    private static String TAG = "FollowFansRecordAdapter";
    private String thisUId = UserProfileManager.getInstance().getLoginUserInfo().getuId();
    public final static int REQUEST_CODE_TO_UserProfileActivity = 0;

    public FollowFansRecordAdapter(Context context, List<User> fansList) {
        this.fansList = fansList;
        this.context = context;

    }

    @Override
    public int getItemCount() {
        if (bol_noData || bol_requestError) {
            return 1;
        }
        return fansList.size();
    }

    @Override
    public int getItemViewType(int position) {
        if (bol_noData) {
            return Constant.ITEM_TYPE_NO_DATA;
        } else if (bol_requestError) {
            return Constant.ITEM_TYPE_REQUEST_ERROR;
        }
        return Constant.ITEM_TYPE_NORMAL;

    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == Constant.ITEM_TYPE_NO_DATA) {
            return new NoDataViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.no__data__layout, parent, false));
        } else if (viewType == Constant.ITEM_TYPE_REQUEST_ERROR) {
            return new RequestErrorViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.request_error_layout, parent, false));
        }

        return new FollowFansRecordAdapter.FollowFansRecordViewHolder(LayoutInflater.from(context).inflate(R.layout.follow_fans_list_item, parent, false));
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
        int viewType = getItemViewType(position);
        if (viewType == Constant.ITEM_TYPE_NO_DATA) {
            NoDataViewHolder noDataViewHolder = (NoDataViewHolder) holder;
            noDataViewHolder.tv_tips.setText("没有数据");
        } else if (viewType == Constant.ITEM_TYPE_NORMAL) {
            FollowFansRecordAdapter.FollowFansRecordViewHolder viewHolder = (FollowFansRecordAdapter.FollowFansRecordViewHolder) holder;

            User fans = fansList.get(position);
            if (fans != null) {
                viewHolder.iv_avatar.setVisibility(View.VISIBLE);
                viewHolder.tv_name.setVisibility(View.VISIBLE);
                //Glide.with(context).load(fans.getAvatar()).diskCacheStrategy(DiskCacheStrategy.ALL).into(viewHolder.iv_avatar);
                GlideLoadUtils.glideLoad(context,fans.getAvatar(),viewHolder.iv_avatar);
                viewHolder.tv_name.setText(fans.getUsername());
                viewHolder.tv_address.setText(fans.getArea());
                viewHolder.follow_fans_item.setOnClickListener(v ->
                        ((Activity) context).startActivityForResult(new Intent(context, UserProfileActivity.class).putExtra(EaseConstant.EXTRA_TARGET_USER_INFO, fans), REQUEST_CODE_TO_UserProfileActivity)
                );
                Button btn_follow = viewHolder.btn_follow;
                if (fans.isAttention()) {
                    btn_follow.setText("已关注");
                }
                btn_follow.setOnClickListener(v ->
                {
                    if (TextUtils.equals(fans.getuId(), UserProfileManager.getInstance().getLoginUserInfo().getuId())) {
                        ConfirmDialog dialog = new ConfirmDialog(context, "提示", "不能关注自己");
                        dialog.show();
                        return;
                    }

                    if (fans.isAttention()) {
                        btn_follow.setText("关注");
                        fans.setAttention(false);
                        removeFollow(fans.getuId());
                    } else {
                        btn_follow.setText("已关注");
                        fans.setAttention(true);
                        follow(fans.getuId());

                    }


                });


            } else {
                viewHolder.iv_avatar.setVisibility(View.INVISIBLE);
                viewHolder.tv_name.setVisibility(View.INVISIBLE);
            }

        }

    }

    @Override
    public long getItemId(int position) {

        return position;
    }

    class FollowFansRecordViewHolder extends RecyclerView.ViewHolder {

        @BindView(R.id.iv_avatar)
        ImageView iv_avatar;
        @BindView(R.id.tv_nick)
        TextView tv_name;
        @BindView(R.id.tv_address)
        TextView tv_address;
        @BindView(R.id.btn_follow)
        Button btn_follow;
        @BindView(R.id.follow_fans_item)
        RelativeLayout follow_fans_item;

        public FollowFansRecordViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);


        }
    }


    public interface InteractionListener {
        void onItemViewClick(String forwardId);

    }

    /**
     * 关注
     *
     * @param targetUid
     */
    private void follow(String targetUid) {
        if (!Helper.getInstance().isNetworkConnected()) {
            ((BaseActivity) context).showToast_v1(context.getString(R.string.network_anomalies));
            return;
        }
        if (ClickUtil.isFastClick()) {
            return;
        }
        if (TextUtils.equals(targetUid, UserProfileManager.getInstance().getLoginUserInfo().getuId())) {
            Toast.makeText(context, "不能关注自己", Toast.LENGTH_LONG).show();
            return;
        }

        Map<String, String> object = new HashMap<>();
        object.put("targetUid", targetUid);

        RetrofitManager.getInstance().createRequest(UserService.class)
                .addAttention(object)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            return;
                        }

                        if (result.isError()) {
                            Log.e(TAG, result.getMsg());
                            return;
                        }
                        Log.i(TAG, "onResponse: 关注成功 targetUid：" + targetUid);
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        ConfirmDialog dialog = new ConfirmDialog(context, "提示", "关注失败");
                        dialog.show();
                    }
                });
    }


    /**
     * 取消关注
     *
     * @param
     */
    private void removeFollow(String followId) {
        if (!Helper.getInstance().isNetworkConnected()) {
            ((BaseActivity) context).showToast_v1(context.getString(R.string.network_anomalies));
            return;
        }
        Map<String, String> object = new HashMap<>();
        object.put("followUId", followId);
        object.put("uId", thisUId);
        RetrofitManager.getInstance().createRequest(UserService.class)
                .removeAttention(object).enqueue(new Callback<CommonResult>() {
            @Override
            public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                CommonResult result = response.body();
                if (!response.isSuccessful() || result == null) {
                    Log.e(TAG, "onResponse: " + response.message());
                    return;
                }
                if (result.isError()) {
                    Log.e(TAG, result.getMsg());
                }
            }

            @Override
            public void onFailure(Call<CommonResult> call, Throwable t) {
                Log.e(TAG, "onFailure: " + t.getMessage());
                ConfirmDialog dialog = new ConfirmDialog(context, "提示", "取消关注失败");
                dialog.show();

            }
        });
    }


    /**
     * 显示普通视图
     * 有数据的时候调用
     */
    public void showNormalView() {
        bol_noData = false;
        bol_requestError = false;
        notifyDataSetChanged();
    }

    /**
     * 显示无数据视图
     */
    public void showNoDataView() {
        bol_noData = true;
        notifyDataSetChanged();
    }

    /**
     * 显示请求数据错误视图
     */
    public void showErrorView() {
        bol_requestError = true;
        notifyDataSetChanged();
    }
}